﻿using System.Configuration;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Components.DictionaryAdapter;
using Castle.Facilities.FactorySupport;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Novagoal.Website.Models.Forms;
using Novagoal.Website.WebApp.Controllers;
using Novagoal.Website.WebApp.ModelBinders;
using Ids.Tools.Castle.Windsor;

namespace Novagoal.Website.WebApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {

        public IWindsorContainer Container { get { return ComponentsProvider.GetInstance().WindsorContainer; } }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterControllerFactory(ControllerBuilder.Current);

            RegisterRoutes(RouteTable.Routes);

            RegisterModelBinders(System.Web.Mvc.ModelBinders.Binders);  
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        private void RegisterControllerFactory(ControllerBuilder controllerBuilder)
        {
            Container.AddFacility<FactorySupportFacility>();

            Container.Register(Component.For<IApplicationSettings>().UsingFactoryMethod(
                () => new DictionaryAdapterFactory().GetAdapter<IApplicationSettings>(ConfigurationManager.AppSettings)));

            controllerBuilder.SetControllerFactory(new ControllersFactory(Assembly.GetExecutingAssembly()));
        }

        private static void RegisterModelBinders(ModelBinderDictionary modelBinderDictionary)
        {
            modelBinderDictionary[typeof (ActivationFormModel)] = new ActivationFormModelBinder();

            modelBinderDictionary[typeof(UserFormModel)] = new UserFormModelBinder();
        }
    }
}